<?php


namespace app\admin\controller;


use app\BaseController;
use think\Exception;

class Category extends BaseController
{
    public function index()
    {
        $pid = input('pid', 0, 'intval');

        $data = [
            'pid' => $pid
        ];

        try {
            validate(\app\admin\validate\Category::class)->scene('index')->check($data);
        } catch (Exception $e) {
            return show(2, $e->getMessage());
        }

        list($categories, $page) = (new \app\admin\business\Category())->getLists($data, 5);

        return view('', [
            'categories' => $categories,
            'page' => $page,
        ]);
    }

    public function add()
    {
        try {
            $categories = (new \app\admin\business\Category())->getNormalCategories();

        } catch (Exception $e) {
            $categories = [];
        }

        return view('', [
            'categories' => json_encode($categories),
        ]);
    }

    public function save()
    {
        $pid = input('pid', 0, 'intval');
        $name = input('name', '', 'trim');
        $data = [
            'pid' => $pid,
            'name' => $name,
        ];

        try {
            validate(\app\admin\validate\Category::class)->scene('add')->check($data);
        } catch (Exception $e) {
            return show(2, $e->getMessage());
        }

        try {
            (new \app\admin\business\Category())->add($data);
        } catch (Exception $e) {
            return show(2, $e->getMessage());
        }
        return show(1, 'ok');
    }

    public function dialog()
    {
        $categories = (new \app\admin\business\Category())->getNormalByPid();
        return view('', [
            'categories' => json_encode($categories),
        ]);
    }

    public function getByPid()
    {
        $pid = input('pid', '', 'intval');
        return show(1,'ok',json_encode((new \app\admin\business\Category())->getNormalByPid($pid)));
    }
}